package com.mingqijia.gassafety.webserver.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.mingqijia.gassafety.authority.api.resp.config.DictionaryItemRespDTO;
import com.mingqijia.gassafety.authority.dal.helper.ConfigureHolder;
import com.mingqijia.gassafety.db.entity.*;
import com.mingqijia.gassafety.db.entity.vo.RecordVO;
import com.mingqijia.gassafety.db.mapper.InformRecordMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mingqijia.gassafety.shared.constant.Constants;
import com.mingqijia.gassafety.shared.constant.PageColumnConst;
import com.mingqijia.gassafety.shared.constant.StrategyTypeEnum;
import com.mingqijia.gassafety.shared.utils.ApplicationUtils;
import com.mingqijia.gassafety.shared.utils.commonUtils.PageColumns;
import com.mingqijia.gassafety.shared.utils.commonUtils.PageUtil;
import com.mingqijia.gassafety.webserver.request.InformRecordRequest;
import com.mingqijia.gassafety.webserver.request.WarningRecordInfoRequest;
import com.mingqijia.gassafety.webserver.response.RecordDetailListResponse;
import com.mingqijia.gassafety.webserver.response.RecordResponse;
import com.mingqijia.gassafety.webserver.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 故障、离线、运行报告的通知记录 服务实现类
 * </p>
 *
 * @author shiying.li
 * @since 2023-12-15
 */
@Service
@Slf4j
public class InformRecordServiceImpl extends ServiceImpl<InformRecordMapper, InformRecord> implements InformRecordService {

    @Autowired
    ConsumerService consumerService;
    @Autowired
    DictionaryService dictionaryService;
    @Autowired
    ConfigureHolder holder;
    @Autowired
    EquipmentService dtuService;
    @Autowired
    ServicePkgRecordService servicePkgRecordService;

    @Override
    public PageUtil<RecordResponse> getList(InformRecordRequest request) {
        log.info("InformRecordRequest入参为：{}", request);
        String spId = ApplicationUtils.getWorkingSpId();
        List<RecordResponse> responseList = new ArrayList<>();
        RecordVO vo = new RecordVO();
        BeanUtils.copyProperties(request, vo);
        vo.setSpId(spId);

        List<Integer> consumerIdList = new ArrayList<>();
        if (!StringUtils.isEmpty(request.getNoticeObject()) || !StringUtils.isEmpty(request.getImei())) {
            if (!StringUtils.isEmpty(request.getNoticeObject())){
                LambdaQueryWrapper<Consumer> lqw = new LambdaQueryWrapper<>();
                lqw.eq(Consumer::getIsDeleted, Constants.IS_DELETED_FALSE).eq(Consumer::getSpId, spId)
                        .and(lqw2 -> lqw2.eq(Consumer::getSubsCode, request.getNoticeObject()).
                                or().eq(Consumer::getCustName, request.getNoticeObject())
                                .or().eq(Consumer::getName, request.getNoticeObject()));
                List<Consumer> consumerList = consumerService.list(lqw);
                consumerIdList = consumerList.stream().map(Consumer::getId).collect(Collectors.toList());
            }
            if (!StringUtils.isEmpty(request.getImei())){
                Dtu deviceByImei = dtuService.getDeviceByImei(request.getImei(), spId);
                if (deviceByImei != null){
                    consumerIdList.add(deviceByImei.getConsumerId());
                }
            }
            if (CollectionUtils.isEmpty(consumerIdList)){
                return new PageUtil<>(request.getPage(), request.getPageSize(),0 , responseList);
            }
        }
        vo.setConsumerIds(consumerIdList);
        Page<RecordResponse> page = PageHelper.startPage(request.getPage(), request.getPageSize());
        List<RecordVO> list = this.baseMapper.getList(vo);
        if (CollectionUtils.isEmpty(list)){
            return new PageUtil<>(request.getPage(), request.getPageSize(), 0 , responseList);
        }
        //行业类型
        List<DictionaryItemRespDTO> industryDictList = holder.getDictionaryByKey(Constants.INDUSTRY_TYPE_CODE);
        List<Integer> consumerIds = new ArrayList<>();
        for (RecordVO recordVO : list) {
            if (recordVO.getStrategyObj() == 2 && !StringUtils.isEmpty(recordVO.getStrategyObjValues())) {
                String[] split = recordVO.getStrategyObjValues().split(";");
                for (String key : split) {
                    if (!StringUtils.isEmpty(key)){
                        consumerIds.add(Integer.valueOf(key));
                    }
                }
            }
        }
        Map<Integer, Consumer> consumerMap;
        if (!CollectionUtils.isEmpty(consumerIds)) {
            List<Consumer> consumerList = consumerService.listByIds(consumerIds);
            if (!CollectionUtils.isEmpty(consumerList)) {
                consumerMap = consumerList.stream().collect(Collectors.toMap(Consumer::getId, Consumer -> Consumer, (a1, a2) -> a1));
            } else {
                consumerMap = new HashMap<>();
            }
        } else {
            consumerMap = new HashMap<>();
        }
        responseList = list.stream().map(item -> {
            RecordResponse recordResponse = new RecordResponse();
            BeanUtils.copyProperties(item, recordResponse);
            recordResponse.setStrategyType(StrategyTypeEnum.matcher(item.getStrategyType()).getMsg());
            recordResponse.setEventTime(recordResponse.getStartTime());
            recordResponse.setStrategyObject("");
            //策略对象
            if (item.getStrategyObj() == 0){
                recordResponse.setStrategyObject("所有客户");
            }else if (item.getStrategyObj() == 1){
                    String[] split = item.getStrategyObjValues().split(";");
                    StringBuilder stringBuilder = new StringBuilder();
                    for (String s : split) {
                        String name = dictionaryService.getName(industryDictList, s);
                        if (!StringUtils.isEmpty(name)){
                            stringBuilder.append(name).append("、");
                        }
                    }
                    if (stringBuilder.length() > 0){
                        stringBuilder.deleteCharAt(stringBuilder.length() - 1);
                    }
                    recordResponse.setStrategyObject(stringBuilder.toString());
            }else if (item.getStrategyObj() == 2){
                if (!StringUtils.isEmpty(item.getStrategyObjValues())){
                    String[] split = item.getStrategyObjValues().split(";");
                    //List<Consumer> consumerList = consumerService.listByIds(Arrays.asList(split));
                    StringBuilder sb = new StringBuilder();
                    for (String key : split) {
                        if (!StringUtils.isEmpty(key)){
                            int cId = Integer.parseInt(key);
                            if (consumerMap.containsKey(cId)) {
                                Consumer consumer = consumerMap.get(cId);
                                if (!StringUtils.isEmpty(consumer.getCustName())) {
                                    sb.append(consumer.getCustName()).append("、");
                                }
                            }
                        }
                    }
                    if (sb.length() > 0) {
                        recordResponse.setStrategyObject(sb.toString().substring(0, sb.toString().length() - 1));
                    }
//                    String s = consumerList.stream().map(Consumer::getCustName)
//                            .filter(name -> !StringUtils.isEmpty(name)).collect(Collectors.joining("、"));
//                    recordResponse.setStrategyObject(s);
                }
            }else if (item.getStrategyObj() == 3){
                if (!StringUtils.isEmpty(item.getStrategyObjValues())){
                    String[] split = item.getStrategyObjValues().split(";");
                    List<ServicePkgRecord> servicePkgRecords = servicePkgRecordService.listByIds(Arrays.asList(split));
                    String s = servicePkgRecords.stream().map(ServicePkgRecord::getPgkName)
                            .filter(name -> !StringUtils.isEmpty(name)).collect(Collectors.joining("、"));
                    recordResponse.setStrategyObject(s);
                }
            }
            return recordResponse;
        }).collect(Collectors.toList());
        return new PageUtil<>(request.getPage(), request.getPageSize(), page.getTotal() , responseList);
    }

    @Override
    public PageUtil<RecordDetailListResponse> getDetailList(WarningRecordInfoRequest request) {
        String spId = ApplicationUtils.getWorkingSpId();
        LambdaQueryWrapper<InformRecord> lqw = new LambdaQueryWrapper<>();
        lqw.eq(InformRecord::getTaskIdentificationCode, request.getTaskIdentificationCode())
                .eq(InformRecord::getIsDeleted, Constants.IS_DELETED_FALSE)
                .eq(InformRecord::getSpId, spId);
        if (request.getSendType() == null) {
            lqw.in(InformRecord::getSendType, 1,2,3);
        }
        Page<InformRecord> page = PageHelper.startPage(request.getPage(), request.getPageSize());
        List<InformRecord> list = this.list(lqw);
        //取出所以id查询当前id是否有子级
        List<Long> ids = list.stream().map(InformRecord::getId).collect(Collectors.toList());
        Map<Long, List<InformRecord>> informMap;
        if (!CollectionUtils.isEmpty(ids)) {
            LambdaQueryWrapper<InformRecord> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.in(InformRecord::getParentId, ids)
                    .eq(InformRecord::getIsDeleted, Constants.IS_DELETED_FALSE);
            List<InformRecord> informRecords = this.list(lambdaQueryWrapper);
            if (!CollectionUtils.isEmpty(informRecords)) {
                informMap = informRecords.stream().collect(Collectors.groupingBy(InformRecord::getParentId));
            } else {
                informMap = new HashMap<>();
            }
        } else {
            informMap = new HashMap<>();
        }
        List<RecordDetailListResponse> collect = list.stream().map(item -> {
            RecordDetailListResponse response = new RecordDetailListResponse();
            BeanUtils.copyProperties(item, response);
            if (!StringUtils.isEmpty(item.getObjLevel())) {
                if (item.getObjLevel().contains(";")) {
                    String[] split = item.getObjLevel().split(";");
                    StringBuilder sb = new StringBuilder();
                    for (String key : split) {
                        sb.append("级别" ).append(key).append(",");
                    }
                    response.setObjLevel(sb.toString().substring(0, sb.toString().length() - 1));
                } else {
                    response.setObjLevel("级别" + item.getObjLevel());
                }
            }
            Consumer consumer = consumerService.getById(item.getConsumerId());
            String consumerInfo = StringUtils.isEmpty(consumer.getCustName())
                    ? consumer.getSubsCode()
                    : StringUtils.isEmpty(consumer.getSubsCode())
                    ? consumer.getCustName()
                    : consumer.getCustName() + "(" + consumer.getSubsCode() + ")";
            response.setConsumerInfo(consumerInfo);
            response.setSendResult(item.getSendResult() == 0 ? "发送成功":item.getSendResult() == 1? "发送失败":"呼叫中（外呼）");
            response.setSendType(item.getSendType() == 1 ? "短信":item.getSendType() == 2? "微信":"外呼");
            if (informMap.containsKey(item.getId())) {
                List<RecordDetailListResponse> listResponseList = new ArrayList<>();
                List<InformRecord> informRecordList = informMap.get(item.getId());
                for (InformRecord informRecord : informRecordList) {
                    RecordDetailListResponse detailListResponse = new RecordDetailListResponse();
                    BeanUtils.copyProperties(informRecord, detailListResponse);
                    if (!StringUtils.isEmpty(informRecord.getObjLevel())) {
                        detailListResponse.setObjLevel("级别" + informRecord.getObjLevel());
                    }
                    Consumer consumerServiceById = consumerService.getById(informRecord.getConsumerId());
                    String consumerServiceInfo = StringUtils.isEmpty(consumerServiceById.getCustName())
                            ? consumerServiceById.getSubsCode()
                            : StringUtils.isEmpty(consumerServiceById.getSubsCode())
                            ? consumerServiceById.getCustName()
                            : consumerServiceById.getCustName() + "(" + consumerServiceById.getSubsCode() + ")";
                    detailListResponse.setConsumerInfo(consumerServiceInfo);
                    detailListResponse.setSendResult(informRecord.getSendResult() == 0 ? "发送成功":"发送失败");
                    detailListResponse.setSendType("短信提醒");
                    listResponseList.add(detailListResponse);
                }
                response.setChildren(listResponseList);
            }
            return response;
        }).collect(Collectors.toList());
        List<PageColumns> pageColumns = PageColumnConst.add(PageColumnConst.runningRecordTitles, PageColumnConst.runningRecordIndices);
        return new PageUtil<>(request.getPage(), request.getPageSize(), page.getTotal(), collect, pageColumns);
    }
}











